package com.supeng.PMdepot.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.supeng.PMdepot.R;
import com.supeng.PMdepot.base.BaseActivity;
import com.supeng.PMdepot.common.Constant;
import com.supeng.PMdepot.entity.ChaiXiangInfo;
import com.supeng.PMdepot.entity.ChaiXiangInsertInfo;
import com.supeng.PMdepot.entity.ServiceResult;
import com.supeng.PMdepot.net.Api;
import com.supeng.PMdepot.net.NetUtils;
import com.supeng.PMdepot.util.KeyboardUtils;
import com.supeng.PMdepot.util.ToastUtils;

import java.math.BigDecimal;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import zpSDK.zpSDK.zpBluetoothPrinter;

public class ChaXiangActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    @BindView(R.id.et_kucun)
    EditText etKucun;
    @BindView(R.id.vv_blue2)
    View vvBlue2;
    @BindView(R.id.tv_cptm)
    TextView tvCptm;
    @BindView(R.id.tv_cpmingcheng)
    TextView tvCpmingcheng;
    @BindView(R.id.tv_zhongliang)
    TextView tvZhongliang;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.vv_blue3)
    View vvBlue3;
    @BindView(R.id.et_cha_weight1)
    EditText etChaWeight1;
    @BindView(R.id.et_cha_count1)
    EditText etChaCount1;
    @BindView(R.id.vv_blue4)
    View vvBlue4;
    @BindView(R.id.et_cha_weight2)
    EditText etChaWeight2;
    @BindView(R.id.et_cha_count2)
    EditText etChaCount2;
    @BindView(R.id.btn_printer)
    Button btnPrinter;
    @BindView(R.id.root_layout)
    LinearLayout rootLayout;
    @BindView(R.id.btn_printerOne)
    Button btnPrinterOne;
    private String chanpin;
    public static BluetoothAdapter myBluetoothAdapter;
    public String SelectedBDAddress;
    private TextView tv_connectBlooth;
    private ChaiXiangInfo chaiXiangInfo;
    private String metChaWeight1str;
    private String metcount1Str;
    private String metChaWeight2str;
    private String metcount2Str;
    private String mtimer;
    private String mbarcode1;
    private String mbarcode2;
    private boolean isChaiXiang=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //弹出键盘滚动问题
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_chaxiang);
        unbinder = ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initData() {

        etKucun.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == 0 || actionId == 6) {
                    if (event == null) {
                        if (actionOk(v)) return true;
                    } else {
                        switch (event.getAction()) {
                            case KeyEvent.ACTION_UP:
                                if (actionOk(v)) return true;
                        }
                    }
                }
                return true;

            }
        });


    }

    private boolean actionOk(TextView v) {
       /* if (!TextUtils.isEmpty(chanpin)) {
            etKucun.setText("");
            ToastUtils.show("请等待上一个条码入库才可以进行下一条码扫描");
            return true;
        }*/
        String search = v.getText().toString();
        etKucun.setText("");
        if (TextUtils.isEmpty(search)) {
            ToastUtils.show("无效二维码");
            return true;
        }
        if (search.indexOf(Constant.ChanPinKey) == 0) {
            chanpin = search;
        } else {
            ToastUtils.show("无效二维码");
            return true;
        }
        //KeyboardUtils.hideSoftInput(v, getActivity());
        if (!TextUtils.isEmpty(chanpin)) {
            searchByServer();
        }
        return false;
    }

    private void searchByServer() {

        Api.searchChaixiang(getActivity(), chanpin, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRecode() == 1) {
                    chaiXiangInfo = (ChaiXiangInfo) rspData;
                    setUI();
                    chanpin = "";
                } else {

                    ToastUtils.show(rspData.getMsg());
                    chanpin = "";
                    chaiXiangInfo = null;
                    setUI();
                }

            }

            @Override
            public void failed(String msg) {

                ToastUtils.show(msg);
                chanpin = "";
                chaiXiangInfo = null;
                setUI();
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, ChaiXiangInfo.class);
    }

    private void setUI() {
        clearAll();
        metChaWeight1str="";
        metcount1Str="";
        metChaWeight2str="";
        metcount2Str="";
        mtimer="";
        mbarcode1="";
        mbarcode2="";
        isChaiXiang=false;
        if (chaiXiangInfo != null && chaiXiangInfo.getInfo() != null) {
            tvCptm.setText(chaiXiangInfo.getInfo().getTiaoma() + "");
            tvCpmingcheng.setText(chaiXiangInfo.getInfo().getChanpinname() + " " + chaiXiangInfo.getInfo().getXinghao());
            tvZhongliang.setText(chaiXiangInfo.getInfo().getZhongliang() + "kg");
            tvCount.setText(chaiXiangInfo.getInfo().getShulian() + "");
            etChaCount1.setEnabled(true);
            etChaWeight1.setEnabled(true);
        } else {
            tvCptm.setText("");
            tvCpmingcheng.setText("");
            tvZhongliang.setText("");
            tvCount.setText("");
            etChaCount1.setEnabled(false);
            etChaWeight1.setEnabled(false);
        }
    }


    private void initView() {
        tvCpmingcheng.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvCpmingcheng.setHorizontallyScrolling(true);
        tv_connectBlooth = findViewById(R.id.tv_connectBlooth);
        SelectedBDAddress = ListBluetoothDevice();
        if (TextUtils.isEmpty(SelectedBDAddress)) {
            ToastUtils.show("请先在系统蓝牙界面配对打印设备");
            finish();
        }
        btnPrinter.setOnClickListener(this);
        etKucun.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                etKucun.setInputType(InputType.TYPE_CLASS_TEXT);
                return false;
            }
        });
        etKucun.setInputType(InputType.TYPE_NULL);
        etChaWeight1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == 5) {
                    weight1ok(v);
                    KeyboardUtils.hideSoftInput(v, getActivity());
                    getJiaoDian(etKucun);
                }
                return true;

            }
        });

        etChaCount1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == 5) {
                    count1ok(v);
                    KeyboardUtils.hideSoftInput(v, getActivity());
                    getJiaoDian(etKucun);
                }
                return true;

            }
        });
        btnPrinterOne.setOnClickListener(this);
    }
    public void getJiaoDian(EditText et){
        et.setFocusable(true);

        et.setFocusableInTouchMode(true);

        et.requestFocus();

        et.findFocus();
    }
    public void clearAll() {
        etChaWeight1.setText("");
        etChaWeight2.setText("");
        etChaCount1.setText("");
        etChaCount2.setText("");
    }

    private boolean weight1ok(TextView v) {
        String text = v.getText().toString();
        if (TextUtils.isEmpty(text) || chaiXiangInfo == null || chaiXiangInfo.getInfo() == null) {
            clearAll();
            return false;
        }
        float textFloat = Float.parseFloat(text);
        if (textFloat >= chaiXiangInfo.getInfo().getZhongliang() || textFloat <= 0) {
            clearAll();
            ToastUtils.show("拆分重量不能大于待拆分总重量并且不能等于0");
            return false;
        }
        etChaWeight2.setText(jisuanzhongliang(chaiXiangInfo.getInfo().getZhongliang(), textFloat) + "");
        int count1 = jisuanshuliang(textFloat, chaiXiangInfo.getInfo().getDanzhong());
//        if(count1>=chaiXiangInfo.getInfo().getShulian()){
//            clearAll();
//            ToastUtils.show("拆分数量不能大于待拆分总数量");
//            return  false;
//        }

        etChaCount1.setText(count1 + "");
        etChaCount2.setText((chaiXiangInfo.getInfo().getShulian() - count1) + "");
        return false;
    }

    private boolean count1ok(TextView v) {
        String text = v.getText().toString();
        if (TextUtils.isEmpty(text) || chaiXiangInfo == null || chaiXiangInfo.getInfo() == null) {
            clearAll();
            return false;
        }
        int shuliang = Integer.parseInt(text);
        if (shuliang >= chaiXiangInfo.getInfo().getShulian()) {
            clearAll();
            ToastUtils.show("拆分数量不能大于待拆分总数量");
            return false;
        }
        int count2 = (chaiXiangInfo.getInfo().getShulian() - shuliang);
        etChaCount2.setText(count2 + "");
        return false;
    }

    private static float jisuanzhongliang(float allzhongliang, float zhongliang) {
        BigDecimal b = new BigDecimal(allzhongliang - zhongliang);
        float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return f1;
    }

    private static int jisuanshuliang(float zhongliang, float danzhong) {
        if(danzhong==0){
            return 0;
        }else {
            BigDecimal b = new BigDecimal(zhongliang * 1000 / danzhong);
            int f1 = b.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            return f1;
        }
    }

    private String ListBluetoothDevice() {

        if ((myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()) == null) {
            Toast.makeText(this, "没有找到蓝牙适配器", Toast.LENGTH_LONG).show();
            return "";
        }

        if (!myBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 2);
        }

        Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() <= 0) return "";
        for (BluetoothDevice device : pairedDevices) {
            if (device.getName().indexOf("XT") != -1) {
                tv_connectBlooth.setText("打印机:" + device.getName());
                return device.getAddress();

            }

        }
        return "";
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_printer:

                saveAndPrinter();
                break;
            case R.id.btn_printerOne:
                if(TextUtils.isEmpty(metChaWeight1str)||TextUtils.isEmpty(metChaWeight2str)){
                    ToastUtils.show("请先拆箱再打印");
                    return;
                }
                Print1(metChaWeight1str, metcount1Str, mtimer, mbarcode1);
                Print1(metChaWeight2str, metcount2Str, mtimer, mbarcode2);
                break;
        }
    }

    private void Print1(String weight, String count, String timer, String barCode) {
        zpBluetoothPrinter zpSDK = new zpBluetoothPrinter(this);
        if (!zpSDK.connect(SelectedBDAddress)) {
            Toast.makeText(this, "连接失败------", Toast.LENGTH_LONG).show();
            return;
        }
        zpSDK.pageSetup(560, 480);
        zpSDK.drawText(31, 14, "流程单号：" , 3, 0, 0, false, false);
        zpSDK.drawText(195, 14, chaiXiangInfo.getInfo().getLiuchengdanhao(), 3, 0, 1, false, false);
        zpSDK.drawText(440, 14, chaiXiangInfo.getInfo().getBiaoqianleibie() + "", 4, 0, 1, false, false);

        zpSDK.drawText(31, 64, "产品名称：", 3, 0, 0, false, false);
        zpSDK.drawText(191, 64, chaiXiangInfo.getInfo().getChanpinname()+"/"+chaiXiangInfo.getInfo().getColor(), 3, 0, 1, false, false);
        zpSDK.drawText(31, 121, "产品规格:", 3, 0, 0, false, false);
        zpSDK.drawText(191, 121, chaiXiangInfo.getInfo().getXinghao(), 3, 0, 1, false, false);
        zpSDK.drawText(31, 178, "工序名称：", 3, 0, 0, false, false);
        zpSDK.drawText(195, 178, chaiXiangInfo.getInfo().getGongxvmingcheng(), 3, 0, 1, false, false);
        zpSDK.drawText(95, 235, "重量:", 3, 0, 0, false, false);
        zpSDK.drawText(191, 235,  weight + "KG", 3, 0, 1, false, false);

        zpSDK.drawText(95, 292, "数量:", 3, 0, 0, false, false);
        zpSDK.drawText(191, 292,  count, 3, 0, 1, false, false);
        zpSDK.drawText(71, 358,  timer, 2, 0, 0, false, false);
        zpSDK.drawText(388, 358, barCode, 2, 0, 0, false, false);
        zpSDK.drawQrCode(367, 180, barCode, 0, 5, 0);
//        zpSDK.drawText(32, 5, "提需求请付款", 4, 0, 0, false, false);
//        zpSDK.drawText(27, 92, "微信付款" , 3, 0, 0, false, false);
//        zpSDK.drawText(48, 135, "谢谢！" , 3, 0, 0, false, false);
//        zpSDK.drawQrCode(322, 37, "wxp://f2f0yGCt10Qz36K3shSRXCCi9HORxaRGHX09", 0, 3, 0);

        // zpSDK.drawBarCode(124,48+100+56+56+80+80+80 , "12345678901234567", 128, false, 3, 60);
        zpSDK.print(0, 1);

        zpSDK.printerStatus();
        int a = zpSDK.GetStatus();

        if (a == -1) { //"获取状态异常------";
            Toast.makeText(this, "获取状态异常-----", Toast.LENGTH_LONG).show();


        }
        if (a == 1) {//"缺纸----------";
            Toast.makeText(this, "缺纸----------", Toast.LENGTH_LONG).show();
        }
        if (a == 2) {
            //"开盖----------";
            Toast.makeText(this, "开盖----------", Toast.LENGTH_LONG).show();
        }
        if (a == 0) {

            //"打印机正常-------";
            // Toast.makeText(this,"打印机正常-------", Toast.LENGTH_LONG).show();
        }


        zpSDK.disconnect();
    }

    private void saveAndPrinter() {
        String etcount1Str = etChaCount1.getText().toString();
        String etcount2Str = etChaCount2.getText().toString();
        String etChaWeight1str = etChaWeight1.getText().toString();
        String etChaWeight2str = etChaWeight2.getText().toString();
        if (TextUtils.isEmpty(etChaWeight1str)) {
            ToastUtils.show("请输入拆分重量");
            return;
        }
        if (TextUtils.isEmpty(etcount1Str)) {
            ToastUtils.show("请输入拆分数量");
            return;
        }
        int count1 = Integer.parseInt(etcount1Str);
        int count2 = Integer.parseInt(etcount2Str);
        float weight1 = Float.parseFloat(etChaWeight1str);
        float weight2 = Float.parseFloat(etChaWeight2str);
        if (count1 <= 0) {
            ToastUtils.show("拆箱1号数量不正确");
            return;
        }
        if (count2 <= 0) {
            ToastUtils.show("拆箱2号数量不正确");
            return;
        }
        if (weight1 <= 0) {
            ToastUtils.show("拆箱1号重量不正确");
            return;
        }
        if (weight2 <= 0) {
            ToastUtils.show("拆箱2号重量不正确");
            return;
        }
        if (chaiXiangInfo == null || chaiXiangInfo.getInfo() == null) {
            ToastUtils.show("请先扫条码或者条码无数据");
            return;
        }
        if(isChaiXiang){
            ToastUtils.show("请勿重复点击");
        }else {
            isChaiXiang = true;
            saveByServer(etcount1Str, etcount2Str, etChaWeight1str, etChaWeight2str);
        }

    }

    private void saveByServer(final String etcount1Str, final String etcount2Str, final String etChaWeight1str, final String etChaWeight2str) {
        Api.chaixiang(getActivity(), chaiXiangInfo.getInfo().getTiaoma(), etChaWeight1str, etcount1Str, etChaWeight2str, etcount2Str, new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRecode() == 1) {
                    ChaiXiangInsertInfo chaiXiangInsertInfo = (ChaiXiangInsertInfo) rspData;
                    metChaWeight1str=etChaWeight1str;
                    metChaWeight2str=etChaWeight2str;
                    metcount1Str=etcount1Str;
                    metcount2Str=etcount2Str;
                    mtimer=chaiXiangInsertInfo.getInfo().getTimer();
                    mbarcode1=chaiXiangInsertInfo.getInfo().getBarode1();
                    mbarcode2=chaiXiangInsertInfo.getInfo().getBarode2();
                    Print1(etChaWeight1str, etcount1Str, chaiXiangInsertInfo.getInfo().getTimer(), chaiXiangInsertInfo.getInfo().getBarode1());
                    Print1(etChaWeight2str, etcount2Str, chaiXiangInsertInfo.getInfo().getTimer(), chaiXiangInsertInfo.getInfo().getBarode2());
//                clearAll();
//                chaiXiangInfo=null;
//                setUI();
//                chanpin="";
                } else {
                    ToastUtils.show(rspData.getMsg());
                    isChaiXiang=false;
                }
            }

            @Override
            public void failed(String msg) {
                ToastUtils.show(msg);
                isChaiXiang=false;
            }

            @Override
            public void onUsedCache(String msg) {

            }
        }, ChaiXiangInsertInfo.class);
    }
}
